<?php
namespace common\helps;
use yii;
 use backend\models\User;
use backend\models\Admin;
/*
 * 自定义全局公共方法
 */
class tools{

    public static function createOrderNo($prefix = 'L')
    {
        return $prefix . (strtotime(date('YmdHis', time()))) . substr(microtime(), 2, 6) . sprintf('%03d', rand(0, 999));
    }

//手机掩码
    public static function maskMobile($mobile) {
        $prefix = substr($mobile, 0, 3);
        $suffix = substr($mobile, -4, 4);
        $maskMobile = $prefix . " **** " . $suffix;
        return $maskMobile;
    }

//银行卡掩码
    public static function maskBankNum($bank) {
        $prefix = substr($bank, 0, 4);
        $suffix = substr($bank, -4, 4);
        $maskBankCardNo = $prefix." **** **** **** ".$suffix;
        return $maskBankCardNo;
    }

    public static function generateRandomString($length = 10) {
        $characters = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
        $randomString = '';
        for ($i = 0; $i < $length; $i++) {
            $randomString .= $characters[rand(0, strlen($characters) - 1)];
        }
        return $randomString;
    }

    public static function createRandomNum($length = 10) {
        $characters = '023456789';
        $randomString = '';
        for ($i = 0; $i < $length; $i++) {
            $randomString .= $characters[rand(0, strlen($characters) - 1)];
        }
        return $randomString;
    }

    public static function getIp(){
        if (!empty($_SERVER['HTTP_CLIENT_IP'])) {
            $ip_address = $_SERVER['HTTP_CLIENT_IP'];
        }
        elseif (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])){
            $ip_address = $_SERVER['HTTP_X_FORWARDED_FOR'];
        }
        else{
            $ip_address = $_SERVER['REMOTE_ADDR'];
        }
        return $ip_address;
    }

    public static function verifyCode(){
        $session = Yii::$app->session;

        $image=imagecreatetruecolor(100, 30);
        //背景颜色为白色
        $color=imagecolorallocate($image, rand(200,220), rand(200,220), rand(200,220));
        imagefill($image, 20, 20, $color);

        $code='';
        for($i=0;$i<4;$i++){
            $fontSize=8;
            $x=rand(5,10)+$i*100/4;
            $y=rand(5, 15);
            $data='023456789';
            $string=substr($data,rand(0, strlen($data)-1),1);
            $code.=$string;
            $color=imagecolorallocate($image,rand(0,120), rand(0,120), rand(0,120));
            imagestring($image, $fontSize, $x, $y, $string, $color);
        }
        $data = [
            'title' => $code,  //数据
            'expire_time' => time() + 180, //这里设置10秒过期
        ];
        $session['code'] = $data;
        //$session->set('code',$code);

        ob_start ();
        //header('content-type:image/png');//定义输出为图像类型
        imagepng($image);//生成图像
        imagedestroy($image);//销毁图像释放内存
        $imageData = ob_get_contents ();
        ob_end_clean ();
        $imageDataBase64 = "data:image/png;base64,". base64_encode ($imageData);
        return $imageDataBase64;
    }

    /**
     * 抛出数据
     * @author hey_heyang(635870453@qq.com)
     */
    public static function outPutData($data){
        $response=  Yii::$app->response;
        $res_data = [
            'success' => $response->isSuccessful,
            'code' => $response->getStatusCode(),
            'message' => $response->statusText,
            'data' => $data,
        ];
        echo json_encode($res_data);
        exit();
    }

    /**
     * 获取登录用户的权限组
     * @param $user_id
     * @author hey_heyang(635870453@qq.com)
     */
    public static function getUserAuth($user_id)
    {
        $redis = Yii::$app->cache;
        $user_auth = $redis->hget('user_auth' ,'user_'.$user_id);
        if(empty($user_auth)){ // 未查询到用户缓存的权限信息,查询并更新缓存
            $user_model = new Admin();
            $user_auth = $user_model->getAuthArray($user_id);
            if(empty($user_auth)){
              return array();
            }
            $redis->hdel('user_auth','user_'.$user_id);
            $redis->hset('user_auth','user_'.$user_id,json_encode($user_auth));

        }else{
            $user_auth = json_decode($user_auth,true);
        }


        return $user_auth;

    }


    /**
     * 获取登录用户的权限组
     * @param $user_id
     * @author hey_heyang(635870453@qq.com)
     */
    public static function getUserMenuAuth($user_id)
    {
        $redis = Yii::$app->cache;
        $user_auth = $redis->hget('user_auth_menu' ,'user_'.$user_id);
        if(empty($user_auth)){ // 未查询到用户缓存的权限信息,查询并更新缓存
            $user_model = new Admin();
            $user_auth = $user_model->getMenuAuthArray($user_id);
            if(empty($user_auth)){
                static::outPutData(code::$auth_error);
            }
            $redis->hdel('user_auth_menu','user_'.$user_id);
            $redis->hset('user_auth_menu','user_'.$user_id,json_encode($user_auth));

        }else{
            $user_auth = json_decode($user_auth,true);
        }


        return $user_auth;

    }

    /**
     * phpexcel导出数据
     * @param $tableheader
     * @param $data
     * @param $filename
     * @author hey_heyang(635870453@qq.com)
     */
    public static  function ToPHPEXECL($tableheader,$data,$filename){
        $dir=dirname(Yii::$app->basePath);
        include_once ($dir.'/common/helps/Classes/PHPExcel.php');
        include_once ($dir.'/common/helps/Classes/PHPExcel/Writer/Excel5.php');
        $excel = new \PHPExcel();
        $letter = array('A','B','C','D','E','F','G','H','I','J','K');
        for($i = 0;$i < count($tableheader);$i++) {
            $excel->getActiveSheet()->setCellValue("$letter[$i]1","$tableheader[$i]");
        }
        for ($i = 2;$i <= count($data) + 1;$i++) {
            $j = 0;
            foreach ($data[$i - 2] as $key=>$value) {
                $excel->getActiveSheet()->setCellValue("$letter[$j]$i","$value");
                $excel->getActiveSheet()->getStyle( "$letter[$j]$i")->getAlignment()->setHorizontal(\PHPExcel_Style_Alignment::HORIZONTAL_JUSTIFY);
                $j++;
            }
        }



        $write = new \PHPExcel_Writer_Excel5($excel);
        header("Pragma: public");
        header("Expires: 0");
        header("Cache-Control:must-revalidate, post-check=0, pre-check=0");
        header("Content-Type:application/force-download");
        header("Content-Type:application/vnd.ms-excel");
        header("Content-Type:application/octet-stream");
        header("Content-Type:application/download");
        header('Content-Disposition:attachment;filename="'.$filename.'.xls"');
        header("Content-Transfer-Encoding:binary");
        $write->save('php://output');
        die;
    }


    /**获取分页后的数据
     * @author hey_heyang(635870453@qq.com)
     */
    public static  function getPageData($data,$page_size,$page){
        if(empty($page_size)) $page_size=10;
        if(empty($page)) $page=1;
        $total_count = count($data);
        $total_page = ceil($total_count/$page_size);
        $data_list = self::pageArray($data,$page_size,$page);
        return array('data'=>empty($data_list)?[]:$data_list,'total_page'=>$total_page,'total_count'=>$total_count);
    }


    /**
     * @param $arr 二维数组源
     * @param $pagesize 每页记录数
     * @param $curpage 当前页码
     * @return array 分页后数组
     * @author hey_heyang(635870453@qq.com)
     */
    public static   function pageArray($arr,$pagesize,$curpage){
        return array_slice($arr,($curpage-1)*$pagesize,$pagesize);
    }


    /**删除权限相关缓存
     * @author hey_heyang(635870453@qq.com)
     */
    public static   function delAuthCache(){
        $redis = Yii::$app->cache;
        $redis->del('user_auth_menu');
        $redis->del('user_auth');
        $redis->del('role_auth');
        return;
    }

    /*
	    发送短信 - 云片网
    */
    public static function SmsToSend($mobile,$code){

        $apikey = 'd3bba9e677e867354029fb4e35c6ab33'; //修改为您的apikey(https://www.yunpian.com)登录官网后获取
        $url = 'https://sms.yunpian.com/v2/sms/single_send.json';
        $tpl_id = '【影沐】您的验证码是'.$code;

        $ch = curl_init();

        /* 设置验证方式 */
        curl_setopt($ch, CURLOPT_HTTPHEADER, array('Accept:text/plain;charset=utf-8', 'Content-Type:application/x-www-form-urlencoded', 'charset=utf-8'));

        /* 设置返回结果为流 */
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

        /* 设置超时时间*/
        curl_setopt($ch, CURLOPT_TIMEOUT, 10);

        /* 设置通信方式 */
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);

        // 发送短信
        $data = array('text' => $tpl_id, 'apikey' => $apikey, 'mobile' => $mobile);

        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($data));
        $json_data = curl_exec($ch);

        $array = json_decode($json_data, true);

        curl_close($ch);

        return $array;
    }

    public static function getMemberInfoByToken(){
        $headers = Yii::$app->request->headers;
        $request =  Yii::$app->request;
        $redis = Yii::$app->cache;
        $token='';
        if(!empty($headers->get('token'))){
            $token =$headers->get('token');
        }elseif(!empty($request->get('token'))){
            $token =$request->get('token');
        }elseif(!empty($request->post('token'))){
            $token =$request->post('token');
        }
        $info = json_decode($redis->hget('member_info', $token),true);
        return $info;
    }

    /*
     * 递归查看用户名是否重复
     * @param Request $request
     * @author cpy(1442435897@qq.com)
     * @return Json
     */
    public static function getMemberName($username){
        $tools = new \common\helps\tools;
        $member = new \frontend\models\Member();
        $res = $member::findOne(['username' => $username]);
        if($res){
            $username = $tools::generateRandomString(6)."用户";
            $tools::getMemberName($username);
        }else{
            return $username;
        }
    }


    /**
      获取毫秒时间戳
     * @author hey_heyang(635870453@qq.com)
   */
    public static  function msectime() {
        list($msec, $sec) = explode(' ', microtime());
        $msectime = (float)sprintf('%.0f', (floatval($msec) + floatval($sec)) * 1000);
        return $msectime;
    }

    /**
     * 判断是否含有其他敏感词汇
     * @param $str
     * @return int bool
     * @author hey_heyang(635870453@qq.com)
     */
    public  static function checkOtherWords($str){
        $path = BASE_PATH.'frontend/otherwords';
        $data =str_replace(array("\n","\r"),"",file_get_contents($path));
        $data = explode(',',$data);
        $badword1 = array_combine($data,array_fill(0,count($data),IS_SENSITIVE));
        $replace_str = strtr($str, $badword1);
        $res  =strpos($replace_str,IS_SENSITIVE);
        return $res;

    }



}
?>